/* eslint-disable react/sort-comp */
/* eslint-disable no-shadow */
import { Component } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { Fragment } from 'react'
import { View, Image, Text } from '@tarojs/components'
import { AtModal, AtIcon } from "taro-ui"
import { connect } from 'react-redux'
import { initLocation, setOpenLocation, updateCity, updateCurrentLocation } from '@/store/location/action'
import { getAccessId, getAliPayAccessId } from '@/store/user/action'
import { carInfo } from '@/store/car/action'
import map from '@/utils/map'
import { getHomePopup, getViewByCityCode, getDefaultAreaInfo } from '@/api'
import { fetchAdd } from '@/api/car'
import { carQrcodeBinding } from '@/api/user'
import HomeView from './components/index'
import onNavigation from '@/utils/command/onNavigation'
import './index.module.scss'
const downIcon = 'https://static3.jekunauto.com/img/platform/down_icon.png'
const locationIcon = 'https://static3.jekunauto.com/img/platform/location_fixed_icon.png'
import { getAreaInfo } from '@/api/platform'
import { pathQueryToJson } from '@/utils'
import { reportCmPV } from '@/utils/cloudMonitorHelper'
import monitor from '@/utils/alipayLogger'

interface State {
  location: IStore | null
  pageLoaded: boolean
  loadLocation: boolean
  advertisement: boolean
  advertisementTime: number
  advertisementGoods: object
  NAV_HEIGHT: number
  NAV_BG: string
  selectArea: object,
  city: object
}


@connect<any>(({ location, user }) => ({ location, user }), _dispatch => ({
  // 缓存 当前区域经纬度，当前区域信息，城市名
  dispatchLocation(params) {
    return _dispatch(initLocation(params))
  },
  // 位置授权状态（true: 已开启，false: 未开启）
  dispatchOpenLocation(status) {
    return _dispatch(setOpenLocation(status))
  },
  dispatchUserInfo() {
    return process.env.TARO_ENV === 'weapp' ? _dispatch(getAccessId()) : _dispatch(getAliPayAccessId())
  },
  dispatchFetchList() {
    return _dispatch(carInfo())
  },
  dispatchCity(params) {
    return _dispatch(updateCity(params))
  },
  dispatchCurrentLocation(params) {
    return _dispatch(updateCurrentLocation(params))
  }
}))

export default class Index extends Component<any> {
  $instance = getCurrentInstance();
  countDown: NodeJS.Timeout
  protected __data__: any
  constructor (props) {
    super(props)

    this.state = {
      location: null,
      pageLoaded: false,
      loadLocation: false,
      advertisement: false,// 是否展示开屏广告
      advertisementTime: 0,// 开屏广告倒计时
      advertisementGoods: {},// 开屏广告跳转参数
      NAV_HEIGHT: 0,
      NAV_BG: '#12b3ff',
      selectArea: {},
      city: {}
    }
    this.__data__ = process.env.TARO_ENV === 'weapp' ? '__data__' : 'data'
  }
  state: State

  isPageShow = false
  pageQuery: any = {}

  static options = {
    addGlobalClass: true
  }
  onLoad(query) {
    if (process.env.TARO_ENV === 'alipay') {
      reportCmPV({ title: '违章查办', query })
    }
  }
  UNSAFE_componentWillMount() { }
  async componentDidMount() {
    if (process.env.TARO_ENV === 'alipay') {
      monitor.api({ api: '集群车宝', success: true, c1: 'taSR_CSH', time: 0 })
    }

    let { scene } = this?.$instance?.router?.params
    let { unionid } = this.props.user.userInfo
    if (scene) {
      let transData = decodeURIComponent(scene)
      this.pageQuery = pathQueryToJson(transData)
    }
    const { dispatchUserInfo } = this.props

    if (!unionid) {
      dispatchUserInfo().then(() => {
        this.getHomeIndex()
      })
    } else {
      this.getHomeIndex()
    }
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    const { cityLocation } = nextProps.location
    let code = this.$instance.router && this?.$instance?.router?.params.storeCode || ''
    if (code) { // 推荐下单门店编码
      Taro.setStorageSync('STORECODE', code)
    }
    if (cityLocation) {
      this.setState({
        city: cityLocation
      })
    }
  }

  componentDidShow() {
    Taro.setStorageSync('IS_RELOAD_STORE_INFO', 0)
    let { dispatchCity } = this.props
    let pages = Taro.getCurrentPages();
    let currentPage = pages[pages.length - 1]; // 获取当前页面
    console.log('currentPage', currentPage)
    if (currentPage[this.__data__].selectArea) { // 获取值
      this.setState({ selectArea: currentPage[this.__data__].selectArea }, () => {
        let current = {
          ...currentPage[this.__data__].selectArea,
        }
        dispatchCity(current)
      })
    }
    const BarColor = Taro.getStorageSync('BarColor')
    console.log('BarColor------------------------', BarColor)
    const app = Taro.getApp()
    this.isPageShow = true
    // 如果缓存了首页标题背景样式，读取缓存
    if (BarColor) {
      Taro.setNavigationBarColor({
        ...BarColor,
      })
      this.setState({
        NAV_BG: BarColor?.backgroundColor
      })
    }
    this.setState({
      NAV_HEIGHT: app.$app.taroGlobalData.NAV_HEIGHT,
    })
  }

  componentDidHide() { this.isPageShow = false }
  componentDidCatchError() { }
  componentDidNotFound() { }
  componentWillUnmount() {
    // 倒计时结束操作
    clearInterval(this.countDown)
  }
  onShareAppMessage() {
    const {
      storeLocation
    } = this.props.location
    if (storeLocation) {
      // 有门店信息，分享带有 storeCode 的门店首页
      const queryStr = encodeURIComponent(`storeCode=${storeLocation.storeCode}`)
      return {
        title: `${storeLocation.storeName}`,
        path: `/pages/tabbar/index/index?scene=${queryStr}`
      }
    } else {
      // 没有门店数据，直接分享平台首页
      return {
        title: '平台首页',
        path: '/pages/tabbar/index/index'
      }
    }
  }

  // 获取车辆列表信息
  getCarInfo = (carId) => {
    Taro.setStorageSync('SCAN_CAR_ID', '')
    Taro.setStorageSync('SCAN_CAR_ID', carId)
  }

  // 车辆建档绑定
  bindCarQrcode = async (token) => {
    try {
      let res = carQrcodeBinding({ token })
      console.log('res', res)
    } catch (err) {
      console.log('err', err)
    }
  }

  // 开屏广告
  getHomePopup = () => {
    console.log('有没有执行开屏广告')
    getHomePopup({}).then(res => {
      const { data: { data, success } } = res
      if (success) {
        // 倒计时大于0且有图片
        if (data.openTime > 0 && data.popImage) {
          this.setState({
            advertisementTime: data.openTime,
            advertisement: true,
            advertisementGoods: {
              popImage: data.popImage,
              linkType: data.linkType,
              linkContent: data.linkContent
            }
          }, () => {
            // 开屏广告倒计时
            this.countDown = setInterval(() => {
              const { advertisementTime } = this.state
              if (advertisementTime > 0) {
                this.setState({
                  advertisementTime: advertisementTime - 1
                })
              } else {
                // 倒计时结束操作
                clearInterval(this.countDown)
                this.setState({
                  advertisement: false,
                  advertisementTime: 0
                })
                Taro.showTabBar()
              }
            }, 1000)
          })
        }
      }
    })
  }

  formatLocation(longitude, latitude) {
    longitude = Number(longitude).toFixed(2),
      latitude = Number(latitude).toFixed(2)
    return {
      longitude: longitude.toString().split('.'),
      latitude: latitude.toString().split('.')
    }
  }

  //获取定位信息
  getHomeIndex = async () => {
    console.log('获取定位信息----')
    let state: any = {
      loadLocation: true
    }
    let _this = this
    this.isPageShow = false
    const { dispatchOpenLocation, location, dispatchCity, dispatchCurrentLocation } = this.props
    if (process.env.TARO_ENV === 'weapp') {
      //获取位置信息
      let curLocation: any = await map.getLocation(true)
      const { cityCode = '' } = this.pageQuery
      const { isOpenLocation } = location
      console.log('curLocation', curLocation)
      console.log('isOpenLocation', isOpenLocation)
      // if (!isOpenLocation) {
      // 当用户开启定位授权，更新状态
      if (curLocation) {
        dispatchOpenLocation(true)
        if (curLocation) { // latitude维度  longitude经度
          let { latitude, longitude } = curLocation
          let location = `${longitude},${latitude}`
          console.log('location', location)
          // let location='115.65199435763888,22.91760009765625' // 陆丰测试经纬度
          dispatchCurrentLocation(curLocation)
          // 获取所在位置城市,传递经纬度坐标字符串，用,隔开
          if (cityCode != '') { // 存在城市编码，不需要去调接口
            getViewByCityCode({
              adCode: cityCode
            }).then(res => {
              let { adCode, name } = res?.data.data
              let current = {
                adCode,
                name,
                districtCode: '',
                latitude: '',
                longitude: ''
              }
              getDefaultAreaInfo({
                adCode
              }).then((resp) => {
                let { areaCode } = resp?.data.data
                current.districtCode = areaCode
                dispatchCity(current)
              }).catch(err => {
                console.log(err)
              })
            })
          } else {

            await getAreaInfo({ location }).then(res => {
              let { data } = res?.data
              let { adCode, name, districtCode, jekunCity } = data
              let current = {
                adCode,
                name,
                districtCode,
                latitude,
                longitude
              }
              if (jekunCity == 1) {
                let CURRENT_LOCATION_INFO = Taro.getStorageSync('CURRENT_LOCATION_INFO')
                if (!CURRENT_LOCATION_INFO) { // 第一次进来，记录当前城市
                  dispatchCity(current)
                }
                if (CURRENT_LOCATION_INFO && CURRENT_LOCATION_INFO.adCode != current.adCode) { // 当前用户不在上一次记录的城市中，提醒
                  Taro.showModal({
                    title: '温馨提示',
                    content: `您目前所在城市【${current.name}】，是否切换城市？`,
                    cancelText: '不用切换',
                    cancelColor: '#999999',
                    confirmText: '立即切换',
                    confirmColor: '#12b3ff',
                  }).then(res => {
                    // 存起来
                    if (res.confirm) {
                      dispatchCity(current)
                    }

                  }).catch(() => {
                  })
                  //
                  return
                }
              } else if (jekunCity == 0) { // 当前所在城市没有车宝门店
                dispatchCity(current)
                Taro.showModal({
                  title: '温馨提示',
                  content: `您所在的城市无服务门店，已帮您自动定位到广州了解集群车宝服务`,
                  cancelColor: '#999999',
                  confirmText: '其他城市',
                  confirmColor: '#12b3ff',
                }).then(res => {
                  // 存起来
                  if (res.confirm) {
                    console.log('this', this)
                    _this.gotoChooseCity()
                  }
                })
              }

            })
          }
        }
      } else { // 没有开启授权，直接拿广州的cityCode
        let location = ''
        await getAreaInfo({ location }).then(res => {
          let { data } = res?.data
          let { adCode, name, districtCode } = data
          let current = {
            adCode,
            name,
            districtCode,
            latitude: '',
            longitude: ''
          }
          dispatchCity(current)
          this.setState({
            city: current
          })

        })
      }
      // }
      state = {
        ...state,
        location: curLocation
      }
      this.setState(state, () => this.storeHome())
    } else {
      var that = this
      const { cityCode = '' } = that.pageQuery
      my.showLoading()
      my.getLocation({
        // type:3,
        async success(res) {
          console.log('支付宝小程序', res)
          let { latitude, longitude } = res
          let location = `${longitude},${latitude}`
          console.log('location', location)
          dispatchCurrentLocation(res)
          // 获取所在位置城市,传递经纬度坐标字符串，用,隔开
          if (cityCode != '') { // 存在城市编码，不需要去调接口
            getViewByCityCode({
              adCode: cityCode
            }).then(res => {
              let { adCode, name } = res?.data.data
              let current = {
                adCode,
                name,
                districtCode: '',
                latitude: '',
                longitude: ''
              }
              getDefaultAreaInfo({
                adCode
              }).then((resp) => {
                let { areaCode } = resp?.data.data
                current.districtCode = areaCode
                dispatchCity(current)
              }).catch(err => {
                console.log(err)
              })
            })
          } else {

            await getAreaInfo({ location }).then(res => {
              let { data } = res?.data
              let { adCode, name, districtCode, jekunCity } = data
              let current = {
                adCode,
                name,
                districtCode,
                latitude,
                longitude
              }
              if (jekunCity == 1) {
                let CURRENT_LOCATION_INFO = Taro.getStorageSync('CURRENT_LOCATION_INFO')
                if (!CURRENT_LOCATION_INFO) { // 第一次进来，记录当前城市
                  dispatchCity(current)
                }
                if (CURRENT_LOCATION_INFO && CURRENT_LOCATION_INFO.adCode != current.adCode) { // 当前用户不在上一次记录的城市中，提醒
                  Taro.showModal({
                    title: '温馨提示',
                    content: `您目前所在城市【${current.name}】，是否切换城市？`,
                    cancelText: '不用切换',
                    cancelColor: '#999999',
                    confirmText: '立即切换',
                    confirmColor: '#12b3ff',
                  }).then(res => {
                    // 存起来
                    if (res.confirm) {
                      dispatchCity(current)
                    }

                  }).catch(() => {
                  })
                  //
                  return
                }
              } else if (jekunCity == 0) { // 当前所在城市没有车宝门店
                dispatchCity(current)
                Taro.showModal({
                  title: '温馨提示',
                  content: `您所在的城市无服务门店，已帮您自动定位到广州了解集群车宝服务`,
                  cancelColor: '#999999',
                  confirmText: '其他城市',
                  confirmColor: '#12b3ff',
                }).then(res => {
                  // 存起来
                  if (res.confirm) {
                    _this.gotoChooseCity()
                  }
                })
              }
            })
          }

          state = {
            ...state,
            location: res
          }
          that.setState(state, () => that.storeHome())
        },
        async fail() {
          console.log('在这里执行了吗----')
          let location = ''
          await getAreaInfo({ location }).then(res => {
            let { data } = res?.data
            let { adCode, name, districtCode } = data
            let current = {
              adCode,
              name,
              districtCode,
              latitude: '',
              longitude: ''
            }
            dispatchCity(current)
            that.setState({
              city: current
            })
            state = {
              ...state,
              location: current
            }
            that.setState(state, () => that.storeHome())
          })

        },
        async finally() {
          my.hideLoading()
        }
      })
      console.log('支付宝小程序流程')
    }
    this.getHomePopup()
  }

  storeHome = async () => {
    const { carRecordId, carLicense, jekunModelCode } = this?.$instance?.router?.params
    if (carRecordId) { // 车辆建档id，如有就直接调取，新用户需要走完注册流程才调取
      this.bindCarQrcode(carRecordId)
    }
    if (carLicense && jekunModelCode) {
      fetchAdd({ // 直接创建车
        carLicense,
        jekunModelCode
      }).then(res => {
        let { data } = res.data
        this.getCarInfo(data.id)
      })
    }
    this.entryInfo()
  }

  // 平台界面显示判单接口
  entryInfo = () => {
    const { user } = this.props
    if (user.userInfo.accessId) {
      const { carRecordId, carLicense, jekunModelCode } = this?.$instance?.router?.params
      if (carRecordId) { // 车辆建档id，如有就直接调取，新用户需要走完注册流程才调取
        this.bindCarQrcode(carRecordId)
      }
      if (carLicense && jekunModelCode) {
        fetchAdd({ // 直接创建车
          carLicense,
          jekunModelCode
        }).then(res => {
          let { data } = res.data
          this.getCarInfo(data.id)
        })
      }
    }
    // 有无登录都需执行
    this.firstGetStoreIndexList()
  }

  // 是否有经纬度判断
  getLocationMsg = (diyLocation?) => {
    const { location } = this.state
    let storeParams: any = null
    if (location) {
      const { latitude: userLatitude, longitude: userLongitude } = diyLocation || location
      storeParams = {
        userLongitude,
        userLatitude
      }
    }
    return storeParams
  }


  // 首次获取平台门店列表页
  firstGetStoreIndexList = async () => {
    this.setState({
      pageLoaded: true
    })
  }

  // 选择城市
  gotoChooseCity() {
    Taro.navigateTo({
      url: `/pages/platform/city/index?type=1`
    })
  }

  // 关闭开屏广告
  closeAdvertisement = () => {
    // 倒计时结束操作
    clearInterval(this.countDown)
    this.setState({
      advertisement: false,
      advertisementTime: 0
    })
  }

  // 点击开屏广告跳转
  goAdvertisement = () => {
    const { advertisementGoods } = this.state
    // 链接类型(1专题2h5 3小程序路径) 由于跟首页约定的不同 所以要另外处理
    let contentType
    switch (advertisementGoods.linkType) {
      case 1:
        contentType = 2
        break;
      case 2:
        contentType = 4
        break;
      case 3:
        contentType = 3
        break;
    }
    const obj = {
      contentType,
      serviceItems: advertisementGoods.linkContent
    }
    onNavigation({ ...obj })
  }

  handleClose = () => { }

  handleCancel = () => { }

  handleConfirm = () => { }


  render() {
    const { pageLoaded, loadLocation, location, city, advertisement, advertisementGoods, NAV_HEIGHT, NAV_BG } = this.state // location
    console.log('NAV_HEIGHT', NAV_HEIGHT)
    let name = Taro.getStorageSync('CURRENT_LOCATION_INFO')?.name || ''
    return loadLocation && city && (
      <View className='main-index' style={{ paddingTop: process.env.TARO_ENV === 'weapp' ? NAV_HEIGHT : 0 }}>
        {
          process.env.TARO_ENV === 'weapp' ?
            <View style={{ height: NAV_HEIGHT, background: NAV_BG, position: 'fixed', top: 0, width: '100%', zIndex: 999999 }}>
              <View className='fixed-location' style={{ top: NAV_HEIGHT - 30 }} onClick={this.gotoChooseCity}>
                <Image src={locationIcon} className="fixed-location--location" mode="aspectFill"></Image>
                <Text className="fixed-location--txt">{name}</Text>
                <Image src={downIcon} className="fixed-location--down" mode="aspectFill"></Image>
              </View>
            </View>
            :
            <View className="alipay-topbar" style={{ position: 'fixed', top: 0, width: '100%', zIndex: 999999, background: NAV_BG }}>
              <View className='fixed-location' style={{ top: '4px' }} onClick={this.gotoChooseCity}>
                <Image src={locationIcon} className="fixed-location--location" mode="aspectFill"></Image>
                <Text className="fixed-location--txt">{name}</Text>
                <Image src={downIcon} className="fixed-location--down" mode="aspectFill"></Image>
              </View>
            </View>
        }
        {
          <Fragment>
            {/* 无定位信息 */}
            <AtModal isOpened={false}
              onClose={this.handleClose}
              onCancel={this.handleCancel}
              onConfirm={this.handleConfirm}
            >
              <View className="location-block">
                <View className="location-block--content">您所在的城市无服务门店，已帮您自动定位到广州了解集群车宝服务</View>
                <View className='location-block--opration'>
                  <View className="location-block--btn location-block--primary" onClick={this.gotoChooseCity}>看看其它城市的门店</View>
                </View>
              </View>
            </AtModal>
          </Fragment>
        }
        {
          location ? (

            pageLoaded && <View className='store-info-wrap'>
              {
                <Fragment>
                  {/* 开屏广告 */}
                  <AtModal isOpened={advertisement} >
                    <View className="advertisement">
                      <Image className="advertisement_img" style={{ 'width': '100%' }} mode="widthFix" src={advertisementGoods.popImage} onClick={() => this.goAdvertisement()} />
                      <AtIcon value='close-circle' size='32' color='#ffffff' onClick={() => { this.closeAdvertisement() }}></AtIcon>
                    </View>
                  </AtModal>
                  <HomeView store={city} query={this?.$instance?.router?.params} />
                </Fragment>
              }
            </View>
          ) : (
            pageLoaded && <View className='store-info-wrap'>
              {
                <HomeView store={city} query={this?.$instance?.router?.params} />
              }
            </View>
          )
        }

      </View>
    );
  }
}
